<template>
  <a-drawer :append-to-body="true" :width="540" title="发起人" :visible="visible" :closable="false" @ok="savePromoter()"
    @cancel="closeDrawer()" ok-text="保存">
    <!-- 发起人设置 -->
    <div class="approval-editor-tab-wrapper">
      <a-radio-group v-model="viewEditorType" type="button" size="large">
        <a-radio :value="0">基础设置</a-radio>
        <a-radio :value="1">表单权限</a-radio>
        <a-radio :value="2">按钮配置</a-radio>
        <!-- <a-radio :value="3">外部交互</a-radio> -->
      </a-radio-group>
    </div>

    <div class="approval-editor-content">
      <!-- 发起人设置 -->
      <div class="item-content-editor" v-if="viewEditorType == 0">
        <div class="content-wrap">
          <div class="item-content" style="margin-top: 24px">
            <div class="type-prompt">谁可以发起该审批</div>
            <a-select class="type-content" v-model="flowPermission.type" @change="handleInitiatorTypeChange"
              placeholder="请选择">
              <a-option :value="0">全员</a-option>
              <a-option :value="1">指定人员</a-option>
              <a-option :value="2">均不可提交</a-option>
            </a-select>
            <template v-if="flowPermission.type == 1">
              <div class="selected-content">
                <div class="selected-list">
                  <a-tag v-for="(item, index) in selected" :key="index">
                    {{ getById(item.id).name }}
                  </a-tag>
                </div>
                <div class="btn" @click="openInitiatorChooseBox()">
                  <a-link>
                    <template #icon><icon-plus /></template>添加
                  </a-link>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
      <!-- 设置表单权限 -->
      <NodeFormAuthSetting v-model:flowNodeConfig="flowNodeConfig" v-else-if="viewEditorType == 1" />
      <!-- 按钮配置 -->
      <NodeButtonSetting v-model:flowNodeConfig="flowNodeConfig" v-else-if="viewEditorType == 2" />
      <!-- 设置操作权限 -->
      <NodeEventSetting v-model:flowNodeConfig="flowNodeConfig" v-else-if="viewEditorType == 3" />
    </div>
  </a-drawer>

  <OrganChooseBox v-model:visible="initiatorChooseBoxVisible" v-model:selected="selected" v-model:organType="organType"
    :only-id="false" />
</template>

<script setup>
import { computed, ref, watch, toRaw } from "vue";
import { useFlowStore, useOrganStore } from "@/stores/index";
import OrganChooseBox from "../dialog/OrganChooseBox.vue";
import { IconPlus } from "@arco-design/web-vue/es/icon";
import NodeFormAuthSetting from "../NodeFormAuthSetting.vue";
import NodeButtonSetting from "../NodeButtonSetting.vue";
import NodeEventSetting from "../NodeEventSetting.vue";
import { ASSIGNEE_TYPE, ASSIGNEE } from "../common/FlowConstant";

let initiatorChooseBoxVisible = ref(false); //初始化指定人员弹窗为false
let selected = ref([]); // 发起人选项
let organType = ref(0); // 指定人员的类型

let flowNodeConfig = ref({});

let flowStore = useFlowStore();
let { getById } = useOrganStore();
let { showPromoterDrawer, setPromoterConfig } = flowStore;
let isPromoterDrawerOpened = computed(() => flowStore.isPromoterDrawerOpened);
let promoterConfig0 = computed(() => flowStore.promoterConfig0);
let visible = computed({
  get: () => isPromoterDrawerOpened.value,
  set: () => closeDrawer(),
});

let viewEditorType = ref(0); // tab编辑类型
let _uid = ref(0);
let flowPermission = ref({ type: 0 });

const openInitiatorChooseBox = () => {
  initiatorChooseBoxVisible.value = true;
};
const formChange = (value) => { };

const handleInitiatorTypeChange = (type) => {
  if (type != 1) selected.value = []; //清除指定人员
};
// 监听发起人设置
watch(promoterConfig0, (newVal) => {
  console.log("promoterConfig0", newVal);
  flowNodeConfig.value = newVal.value;
  flowPermission.value = newVal.flowPermission;
  selected.value = newVal.flowPermission.flowInitiators;
  _uid = newVal.id;
});

const OrganTypeMap = {
  0: ASSIGNEE_TYPE[10],
  1: ASSIGNEE_TYPE[3],
  2: ASSIGNEE_TYPE[4],
};
const TypeMap = {
  0: ASSIGNEE_TYPE[12],
  1: OrganTypeMap[organType.value],
  2: ASSIGNEE_TYPE[11],
};

// 发起人设置保存
const savePromoter = () => {
  console.log("savePromoter", flowPermission.value, organType.value);
  // 发起节点设置 start
  flowNodeConfig.value.assignees = [];
  if (selected.value && selected.value.length > 0) {
    // 分类字段处理
    let selectGroups = groupBy(selected.value, (item) => item.type);
    console.log("22", selectGroups);
    const keys = Object.keys(selectGroups);
    const assignees = keys.map((key) => {
      let dynamicKey = key == 1 ? 'roles' : 'assignees'
      return {
        assigneeTypeEnum: OrganTypeMap[key],
        assigneeType: ASSIGNEE[OrganTypeMap[key]],
        [dynamicKey]: selectGroups[key].map((item) => item.id),
      };
    });
    console.log("33", assignees);
    flowNodeConfig.value.assignees = assignees;
  } else {
    flowNodeConfig.value.assignees.push({
      assigneeTypeEnum: TypeMap[flowPermission.value.type],
      assigneeType: ASSIGNEE[TypeMap[flowPermission.value.type]],
    });
  }

  console.log("flowNodeConfig", flowNodeConfig.value);
  // 发起节点设置 end
  flowPermission.value.flowInitiators = selected.value;
  setPromoterConfig({
    value: toRaw(flowNodeConfig.value),
    flowPermission: toRaw(flowPermission.value),
    // value: toRaw(flowPermission.value),
    flag: true,
    id: _uid,
  });
  closeDrawer();
};
// 分组
const groupBy = (array, key) => {
  const uniqueArray = array.reduce((result, currentItem) => {
    const groupKey =
      typeof key === "function" ? key(currentItem) : currentItem[key];
    if (!result[groupKey]) {
      result[groupKey] = [];
    }
    result[groupKey].push(currentItem);
    return result;
  }, {});
  return uniqueArray;
};
const closeDrawer = () => {
  showPromoterDrawer(false);
};
</script>

<style lang="less">
.approval-editor-tab-wrapper {
  user-select: none;
  margin-bottom: 24px;

  .arco-radio-group-button {
    width: 100%;

    .arco-radio-button {
      flex: 1;
      text-align: center;
    }
  }
}

.approval-editor-content {
  .item-content-editor {
    user-select: none;
    margin-top: 0;

    .type-content {
      margin-top: 8px;
    }

    .selected-content {
      margin-top: 10px;
      display: flex;
      align-items: center;
      gap: 4px;

      .selected-list {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        gap: 4px;
      }
    }
  }
}
</style>
